package org.anderground.editor.gui.menubar;

import static org.anderground.core.Logger.i;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.anderground.editor.gui.MainWindow;
import org.anderground.editor.model.EditorModel;
import org.anderground.editor.storage.WritersRegistry;

/**
 * 
 * @author Ilya Shurigyn
 * 
 */
@SuppressWarnings("serial")
public class SaveMapMenuItem extends JMenuItem {

	public SaveMapMenuItem() {
		super("Save map");
		addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				showSaveFileDialog(SaveMapMenuItem.this);

			}

		});
	}

	/**
	 * show save dialog
	 * 
	 * @param c
	 *            parent component
	 * @return save window(JFileChooser) result code
	 */
	public static int showSaveFileDialog(Component c) {
		JFileChooser fc = new JFileChooser();
		for (WritersRegistry.FileFormat format : WritersRegistry.getFormats()) {
			FileFilter ff = new FileNameExtensionFilter(
					format.shortFileFormatDescription,
					format.formatFileNameExtension);
			fc.addChoosableFileFilter(ff);
		}
		fc.setFileFilter(fc.getChoosableFileFilters()[1]); // set default
		// FileFilter to
		// AndroidMap;

		int dialogResult = fc.showSaveDialog(c);
		if (dialogResult == JFileChooser.APPROVE_OPTION) {
			File f = fc.getSelectedFile();
			i("selected file: " + f.getName());

			String currentExtension = ((FileNameExtensionFilter) fc
					.getFileFilter()).getExtensions()[0];
			String filePath = f.getAbsolutePath();
			if (filePath.indexOf('.') == -1) {
				filePath += "." + currentExtension;
			}
			EditorModel.getInstance().save(filePath);
			MainWindow.modelChangedAfterLastSave = false;
		}
		return dialogResult;

	}
}
